package me.ingxin.android.router

import android.app.Application
import android.content.Context
import android.content.res.AssetManager
import android.content.res.Configuration
import android.content.res.Resources
import me.ingxin.android.router.base.ApplicationComponent
import me.ingxin.android.router.base.BaseComponent

/**
 * Created by ingxin on 2022/4/29
 */
class ComponentManager private constructor() : BaseComponent() {

    private val components = ArrayList<BaseComponent>()

    init {
        Store.instance.getComponents().forEach {
            try {
                val component = it.destination.newInstance() as BaseComponent
                components.add(component)
            } catch (ex: Exception) {
                ex.printStackTrace()
            }
        }
    }

    override fun attachBaseContext(application: Application, base: Context?) {
        components.forEach { it.attachBaseContext(application, base) }
    }

    override fun onCreate(application: Application) {
        components.forEach { it.onCreate(application) }
    }

    override fun onConfigurationChanged(application: Application, newConfig: Configuration) {
        components.forEach { it.onConfigurationChanged(application, newConfig) }
    }

    override fun onLowMemory(application: Application) {
        components.forEach { it.onLowMemory(application) }
    }

    override fun onTrimMemory(application: Application, level: Int) {
        components.forEach { it.onTrimMemory(application, level) }
    }

    fun getResources(resources: Resources?): Resources? {
        val appComponent =
            components.firstOrNull { it is ApplicationComponent } as? ApplicationComponent
        if (appComponent != null) {
            return appComponent.getResources(resources)
        }
        return resources
    }

    fun getAssets(assetManager: AssetManager?): AssetManager? {
        val appComponent =
            components.firstOrNull { it is ApplicationComponent } as? ApplicationComponent
        if (appComponent != null) {
            return appComponent.getAssets(assetManager)
        }
        return assetManager
    }

    companion object {
        @JvmStatic
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { ComponentManager() }
    }

}